package hos.okhttp.http;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;

import hos.okhttp.utils.OkHttpFileUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * <p>Title: FileRequestBody </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/2/24 23:08
 */
public class FileRequestBody extends RequestBody {

    private final File file;

    public FileRequestBody(File file) {
        this.file = file;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return OkHttpFileUtils.mediaType(file);
    }

    @Override
    public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
        Source source = Okio.source(file);
        try {
            bufferedSink.writeAll(source);
        } finally {
            try {
                source.close();
            } catch (Exception ignored) {
            }
        }
    }
}
